package com.aidong.util;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

public class HttpEncodeFormContentFilter implements Filter {
	protected static final String FORM_CHARSET = "UTF-8";

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}
	
	
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		
		Map<String, String[]> allParams =new HashMap<>(request.getParameterMap());
		if (StringUtils.isNotBlank(request.getHeader("cityid"))) {
			allParams.put("cityId", new String[] { request.getHeader("cityid") });
		}
		
		Map<String,String[]> map=request.getParameterMap();
	    for(Iterator iter = map.entrySet().iterator();iter.hasNext();){ 
	        Map.Entry element = (Map.Entry)iter.next(); 
	        Object strKey = element.getKey();
	        
	        String[] value=(String[])element.getValue(); 
	        String valueStr="";
	        for(int i=0;i <value.length;i++){ 
	            valueStr = value[i];
	        }
		  if("storeId ".equals(strKey)){
			  allParams.put("storeId", new String[] { valueStr });
		  }else if("autoId ".equals(strKey)){
	    		 allParams.put("autoId", new String[] { valueStr }); 
		  }
	    }
		ParameterRequestWrapper enhancedHttpRequest = new ParameterRequestWrapper((HttpServletRequest) request,
				allParams);
		filterChain.doFilter(enhancedHttpRequest, response);
	}
	public static String CheckAgent(String agent)    
	{    
		String flag = "";    
	  
	    String[] keywords = { "Android", "iPhone", "iPod", "iPad"};    
	  
	       //排除 Windows 桌面系统    
	        if (!agent.contains("Windows NT") || (agent.contains("Windows NT") && agent.contains("compatible; MSIE 9.0;")))    
	        {    
	            //排除 苹果桌面系统    
	            if (!agent.contains("Windows NT") && !agent.contains("Macintosh"))    
	            {    
	                for (String item : keywords)    
	                {    
	                    if (agent.contains(item))    
	                    {    
	                        flag = item;    
	                        break;    
	                    }    
	                }    
	            }    
	        }    
	  
	    return flag;    
	}    
	@Override
	public void destroy() {
	}
}